var title = "订单";
var config = {
    url_page: _dir + "orderManager.html",
    url_add: _dir + "orderManager_add.html",
    title_page: title + "查询",
    title_list: title + "列表",
    title_add: "添加" + title,
    title_edit: "修改" + title,
    code_list: "/orders/query",
    code_delete: "/orders/del",
    code_add: "/orders/add",
    code_edit: "/orders/update",
    // code_dataUpload: "/book/coverUpload",
    code_imgUpload: "/orders/upload",
    pagination_01: $("#page_01")
};
$(document).ready(function () {
    var defaultImg='../assets/defaultimg.jpg';

    if (_page == "orderManager") {
        // if($(".select2").length > 0){
        //     $(".select2").select2();
        // }
        var pageNo = 1;
        setTitle_01(config['title_list'], config['title_page'], config['url_add']);
        // setDefaultDate($("#startTime"),$("#endTime"))
        //加载事件
        var _trs, _pageSize, _pageCount;
        var setData = function (pIndex, pSize) {
            pIndex = pIndex || 1;
            pSize = pSize || 20;
            var pageSetBody = { "pageNo": pIndex, "pageSize": pSize };
            var sendObj = {
                "userName": $("#userName").val(),
                "userTel": $("#userTel").val(),
                "orderNo": $("#orderNo").val(),
                "goodsName": $("goodsName").val(),
                "waybillNo": $("#waybillNo").val(),
                "orderState": $("#orderState").val(),
            };
            window.sessionStorage.setItem(_page+"data",JSON.stringify({
                'sendObj':sendObj,
                'pageSetBody':pageSetBody
            }));
            $.extend(sendObj,pageSetBody);
            _call(config['code_list'], sendObj, function (res) {
                _trs = "";
                if (!res.body || res.body.length == 0) {
                    _trs = "";
                    _pageSize = 1;
                    _pageCount = 1;
                    pageNo--
                    $("#table_01 tbody").html('');
                    d_alert('警告','没有更多数据啦！','warning')
                }
                else {
                    _pageSize = res.body.pageSize;
                    _pageCount = res.body.count;
                    $.each(res.body, function (i, v) {
                        _trs = _trs + `<tr>
                            <td>${dataIsNull(v['id'])}</td>
                            <td>${dataIsNull(v['name'])}</td>
                            <td>${dataIsNull(v['tel'])}</td>
                              <td>
                               <img style="width: 30px;height: 30px;" src="${v['headImg']?v['headImg']:defaultImg}" alt="">

                             </td>
                            <td>${dataIsNull(v['clientUserId'])}</td>
                            <td>${dataIsNull(v['goodsId'])}</td>
                            <td>${dataIsNull(v['orderNo'])}</td>
                            <td>${dataIsNull(v['waybillNo'])}</td>
                            <td>${dataIsNull(v['integral'])}</td>
                            <td>${dataIsNull(v['num'])}</td>
                            <td>${dataIsNull(v['userName'])}</td>
                            <td>${dataIsNull(v['userTel'])}</td>
                            <td>${dataIsNull(v['userAddr'])}</td>
                            <td>${dataIsNull(v['goodsName'])}</td>

                            <td>${dataIsNull(v['orderState'])==1?'预约':dataIsNull(v['orderState'])==2?'支付（未审核）':dataIsNull(v['orderState'])==3?'待审核':dataIsNull(v['orderState'])==4?'审核通过':'关闭'}</td>
                            <!--<td>${dataIsNull(v['recommendCount'])}</td>-->
                            <!--<td>${dataIsNull(v['addr'])}</td>-->
                            <!--<td>${dataIsNull(v['integral'])}</td>-->
                            <!--<td>${dataIsNull(v['remark'])}</td>-->
                            <td>${dataIsNull(v['remark'])}</td>
                             <td>${getTdOperate(5, config['url_add'], v.id, "id", v.id)}</td>
                        </tr>`;
                    });
                    setPageData(res.body);
                    $("#table_01 tbody").html(_trs);
                }

            });
        };

        var loadingAll = function () {
            //初始化加载数据
            setData();
        }

        autoSearchByCookie(loadingAll);
        //查询方法
        loadingAll();
        $(".homePage").click(function(){
            pageNo = 1
            setData(pageNo)
        })
        $(".prevPage").click(function(){
            if(pageNo > 1){
                pageNo--
                setData(pageNo)
            }else{
                d_alert("警告",'已经到头啦！','warning')
            }
            
        })
        $(".nextPage").click(function(){
            pageNo++
            setData(pageNo)
        })
        //查询方法
        setQuery(setData)
    }
    else if (_page == "orderManager_add") {
        var sendObj2 = {};

        if($(".select2").length > 0){
            $(".select2").select2();
        }
        $(".select2").change(function(){
            var val=$('.select2').val()
            if(val==4){
                $('#orderNumberContent').css({display:'block'})
                $('#remarkContent').css({display:'none'})
            }else if(val==5){
                $('#remarkContent').css({display:'block'})
                $('#orderNumberContent').css({display:'none'})
            }else {
                $('#orderNumberContent').css({display:'block'})
                $('#remarkContent').css({display:'none'})
            }
        });



        //初始化
        var PageInit = function () {
            var _fid = $.trim($.request.queryString["fid"]);
            var _fstaffNo = $.trim($.request.queryString["id"]);
            var _rtype = $.trim($.request.queryString["rtype"]);
            var _msgId = 0;
            this.get_fid = function () {
                return this._fid;
            };
            this.get_msgId = function () {
                return this._msgId;
            };
            this.set_fid = function (v) {
                this._fid = v;
            }
            this.set_msgId = function (v) {
                this._msgId = v;
            }
            this.setDefault = function (v) {
                if (_fid == "" && _fstaffNo == "" && _rtype == "") {
                    //添加
                    this.set_msgId(config['code_add']);
                    this.set_fid(0);
                    setTitle_02(config['title_add'],config['url_page']);

                }
                else if (_fid != "" && _fstaffNo != "" && _rtype == "edit") {
                    //修改
                    this.set_msgId(config['code_edit']);
                    this.set_fid(_fid);
                    setTitle_02(config['title_edit'],config['url_page']);
                    sendObj2['id'] = _fid;


                    if (getPageData(_fstaffNo)) {
                        var _v = getPageData(_fstaffNo);
                        var formObj = new Form();
                        formObj.init(_v);
                        if(_v.orderState==4){
                            $('#orderNumberContent').css({display:'block'})
                            $('#remarkContent').css({display:'none'})
                        }else if(_v.orderState==5){
                            $('#remarkContent').css({display:'block'})
                            $('#orderNumberContent').css({display:'none'})
                        }else {
                            $('#orderNumberContent').css({display:'block'})
                            $('#remarkContent').css({display:'none'})
                        }
                    }
                }

            }
        };
        var _default = new PageInit();
        _default.setDefault();

        //提交事件
        $(".validate-form .submit").on("click", function () {
            var _this = $(this);
            if ($(".validate-form").validate().form()) {
                sendObj2["userName"] = $("#userName").val();
                sendObj2["userTel"] = $("#userTel").val();
                sendObj2["userAddr"] = $("#userAddr").val();
                sendObj2["coverUrl"] = $("#coverUrl").val();
                sendObj2["orderState"] = $("#orderState").val();
                sendObj2["waybillNo"] = $("#waybillNo").val();
                sendObj2["remark"] = $("#remark").val();
                _call(_default.get_msgId(), sendObj2, function (res) {
                    confirm_add_ok(res, config['url_page'], function () {
                        window.location.href = window.location.href;
                    });
                });

            }
        });
    }
     $(".select2").select2();
});



//排序 tableId: 表的id,iCol:第几列 ；dataType：iCol对应的列显示数据的数据类型
function sortAble(th, tableId, iCol, dataType) {
    var ascChar = "▲";
    var descChar = "▼";
    var table = document.getElementById(tableId);
    //排序标题加背景色
    for (var t = 0; t < table.tHead.rows[0].cells.length; t++) {
        var th = $(table.tHead.rows[0].cells[t]);
        var thText = th.html().replace(ascChar, "").replace(descChar, "");
        if (t == iCol) {
            th.css("background-color", "#ccc");
        }
        else {
            th.css("background-color", "#fff");
            th.html(thText);
        }
    }
    var tbody = table.tBodies[0];
    var colRows = tbody.rows;
    var aTrs = new Array;
    //将得到的行放入数组，备用
    for (var i = 0; i < colRows.length; i++) {
        //注：如果要求“分组明细不参与排序”，把下面的注释去掉即可
        //if ($(colRows[i]).attr("group") != undefined) {
        aTrs.push(colRows[i]);
        //}
    }
    //判断上一次排列的列和现在需要排列的是否同一个。
    var thCol = $(table.tHead.rows[0].cells[iCol]);
    if (table.sortCol == iCol) {
        aTrs.reverse();
    } else {
        //如果不是同一列，使用数组的sort方法，传进排序函数
        aTrs.sort(compareEle(iCol, dataType));
    }
    var oFragment = document.createDocumentFragment();
    for (var i = 0; i < aTrs.length; i++) {
        oFragment.appendChild(aTrs[i]);
    }
    tbody.appendChild(oFragment);
    //记录最后一次排序的列索引
    table.sortCol = iCol;
    //给排序标题加“升序、降序” 小图标显示
    var th = $(table.tHead.rows[0].cells[iCol]);
    if (th.html().indexOf(ascChar) == -1 && th.html().indexOf(descChar) == -1) {
        th.html(th.html() + ascChar);
    }
    else if (th.html().indexOf(ascChar) != -1) {
        th.html(th.html().replace(ascChar, descChar));
    }
    else if (th.html().indexOf(descChar) != -1) {
        th.html(th.html().replace(descChar, ascChar));
    }
    //重新整理分组
    var subRows = $("#" + tableId + " tr[parent]");
    for (var t = subRows.length - 1; t >= 0 ; t--) {
        var parent = $("#" + tableId + " tr[group='" + $(subRows[t]).attr("parent") + "']");
        parent.after($(subRows[t]));
    }
}
//将列的类型转化成相应的可以排列的数据类型
function convert(sValue, dataType) {
    switch (dataType) {
        case "int":
            return parseInt(sValue, 10);
        case "float":
            return parseFloat(sValue);
        case "date":
            return new Date(Date.parse(sValue));
        case "string":
        default:
            return sValue.toString();
    }
}
//排序函数，iCol表示列索引，dataType表示该列的数据类型
function compareEle(iCol, dataType) {
    return function (oTR1, oTR2) {
        var vValue1 = convert(removeHtmlTag($(oTR1.cells[iCol]).html()), dataType);
        var vValue2 = convert(removeHtmlTag($(oTR2.cells[iCol]).html()), dataType);
        if (vValue1 < vValue2) {
            return -1;
        }
        else {
            return 1;
        }
    };
}
//去掉html标签
function removeHtmlTag(html) {
    return html.replace(/<[^>]+>/g, "");
}

//点击分组行时，切换分组明细的显示/隐藏
function showSub(a) {
    var groupValue = $(a).parent().parent().attr("group");
    var subDetails = $("tr[parent='" + groupValue + "']");
    subDetails.toggle();
}